package labox.innovation.gameserver.datatables;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javolution.util.FastMap;
import labox.innovation.config.Config;

public class MerchantItemsConfig {
	private static final Logger _log = LoggerFactory.getLogger(MerchantItemsConfig.class.getName());

	private static final MerchantItemsConfig _instance = new MerchantItemsConfig();
	
	private FastMap<Integer, String> items;
	
//	private static long timer;
	
	private MerchantItemsConfig() {
		items = new FastMap<Integer, String>();
		loadConfig();
	}
	
	private void loadConfig() {
		FileInputStream fs = null;
		
		try {
			File f = new File(Config.DATAPACK_ROOT, "/data/MerchantItemsConfig.xml");
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			fs = new FileInputStream(f);
			Document document = builder.parse(fs);
			Element root;
			root = document.getDocumentElement();
			
			if (root.getTagName().compareTo("MerchantItems") != 0) {
				throw new Exception("Not a repair file!");
			}
			
			Element parentNode = null;
			Element childNode = null;
			NodeList childList = null;
			NodeList list = root.getElementsByTagName("Npc");
			
			for (int i = 0; i < list.getLength(); i++) {
				parentNode = (Element)list.item(i);
				int key = Integer.parseInt(parentNode.getAttribute("id"));
				childList = parentNode.getElementsByTagName("Items");
				
				for (int j =0; j < childList.getLength(); j++) {
					childNode = (Element)childList.item(j); 
					items.put(key, childNode.getTextContent());
				}
			}
		} catch(Exception e) {
			_log.error("读取NPC商人商品配置文件出错", Config.SERVER_ID, e);
		} finally {
			try {
				fs.close();
			} catch(IOException e) {
				_log.error("读取NPC商人商品配置文件关闭输入流时出错", Config.SERVER_ID, e);
			}
			
		}
				
//		timer = System.currentTimeMillis();
	}
	
	public static MerchantItemsConfig getInstance() {
//		if ((System.currentTimeMillis() - timer) > 60 * 1000) {  //-- 超过1分钟刷新一次
//			_instance.loadConfig();
//		}
		
		return _instance;
	}
	
	/**
	 * 根据NpcID获取itemID列表
	 * @param NpcID
	 * @return
	 */
	public String getItemsByNpcID(int NpcID) {
		return items.get(NpcID);
	}
	
	public static void main(String args[]) {
		System.out.println(MerchantItemsConfig.getInstance().getItemsByNpcID(5));
		System.out.println(MerchantItemsConfig.getInstance().getItemsByNpcID(2));
	}
}
